package com.gupaoedu.vip.mall.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupaoedu.vip.mall.goods.mapper.BrandMapper;
import com.gupaoedu.vip.mall.goods.mapper.CategoryMapper;
import com.gupaoedu.vip.mall.goods.mapper.SkuMapper;
import com.gupaoedu.vip.mall.goods.mapper.SpuMapper;
import com.gupaoedu.vip.mall.goods.model.*;
import com.gupaoedu.vip.mall.goods.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class SpuServiceImpI extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 产品发布--保存功能
     *
     * @param product
     */
    @Override
    public void saveProduct(Product product) {
        //1.保存Spu
        Spu spu = product.getSpu();
        //补充spu信息
        spu.setIsMarketable(1);//已上架
        spu.setIsDelete(0); //未删除
        spu.setStatus(1); //已审核
        spuMapper.insert(spu);
        //2.保存List<Sku>
        Date date = new Date();
        Category category = categoryMapper.selectById(spu.getCategoryThreeId());
        Brand brand = brandMapper.selectById(spu.getBrandId());
        for (Sku sku : product.getSkus()) {
            //SKU名称
            // {"适合人群":"有一定java基础的人","书籍分类":"科技"}
            String name = spu.getName();
            Map<String, String> skuattrMap = JSON.parseObject(sku.getSkuAttribute(), Map.class);
            for (Map.Entry<String, String> entry : skuattrMap.entrySet()) {
                name += "  " + entry.getValue();
            }
            sku.setName(name);
            sku.setCreateTime(date);//创建时间
            sku.setUpdateTime(date); //修改时间
            sku.setCategoryId(spu.getCategoryThreeId()); //分类ID
            sku.setBrandName(brand.getName());  //分类名字
            sku.setBrandId(spu.getBrandId()); //品牌ID
            sku.setCategoryName(category.getName());//品牌名字
            sku.setSpuId(spu.getId()); //spuid
            sku.setStatus(1);  //状态 商品状态 1-正常，2-下架，3-删除
            skuMapper.insert(sku);  //添加
        }
    }
}
